package com.example.administrator.basedemos.activity;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.basedemos.R;
import com.example.administrator.basedemos.adapter.HotExchangeAdapter;
import com.example.administrator.basedemos.adapter.MainMultiItemAdapter;
import com.example.administrator.basedemos.bean.MainItem;
import com.example.administrator.basedemos.utils.Constants;
import com.example.administrator.basedemos.utils.LogUtil;
import com.example.administrator.basedemos.utils.RecycleUtil;
import com.example.administrator.basedemos.utils.TmtUtils;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;

/**
 * 创建者     ZCL
 * 创建时间   2018/7/6 14:42
 * 描述	      ${TODO}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class MarketSearchActivity extends BaseZcActivity implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    private static final String TAG = "MarketSearchActivity";
    @BindView(R.id.market_search_edt)
    EditText     mMarketSearchEdt;
    @BindView(R.id.market_search_cancel)
    TextView     mMarketSearchCancel;
    @BindView(R.id.recyclerview_mm)
    RecyclerView mRecyclerviewMm;
    @BindView(R.id.recyclerview_mw)
    RecyclerView mRecyclerviewMw;
    @BindView(R.id.search_edt_close)
    ImageView    mSearchEdtClose;
    private ArrayList<MainItem>  mList;
    private HotExchangeAdapter   mAdapterEdt;
    private ArrayList<String>    mListFlow;
    private MainMultiItemAdapter mAdapter;
    private ArrayList<String> mListKey;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_market_search;
    }

    @Override
    protected void initData() {
        mToolbarLy.setVisibility(View.GONE);

        mToolbarLy.setVisibility(View.GONE);
        mListFlow = new ArrayList<>();
        mListFlow.add("BatteryView.txt");
        mListFlow.add("一张为view背景（白圈）");
        mListFlow.add("两张图片为资源");
        mListFlow.add("形成圆形波浪效果");
        mListFlow.add("使用自定义view，并传入属性值");
        mListFlow.add("一张为一个圆形");
        mListFlow.add("BatVt");
        mListFlow.add("为自度");
        mListFlow.add("两张图");
        mListFlow.add("为自度");
        mListFlow.add("一张为");
        mListFlow.add("两");

        ArrayList<String> listP = new ArrayList<>();
        listP.add("BatVt");
        listP.add("为自度");
        listP.add("一张为");
        listP.add("两张图");
        listP.add("用于de");
        listP.add("形成圆");
        listP.add("使用自");
        listP.add("一张为");

        mMarketSearchCancel.setFocusable(true);
        mMarketSearchCancel.setFocusableInTouchMode(true);
        mMarketSearchCancel.requestFocus();

        mList = new ArrayList<MainItem>();
        mList.add(new MainItem(Constants.search_flow, mListFlow));
        mList.add(new MainItem(Constants.popular_currency, listP));
        mList.add(new MainItem(Constants.hot_exchange, listP));

        setLayoutMangerVertical(mRecyclerviewMm);
        mAdapter = new MainMultiItemAdapter(mList);
        mRecyclerviewMm.setAdapter(mAdapter);

        mAdapterEdt = new HotExchangeAdapter(R.layout.item_currency, mListFlow);
        mAdapterEdt.setEmptyView(R.layout.empty_view, (ViewGroup) mRecyclerviewMw.getParent());//必须用这个否则please bind recyclerView first!
        RecycleUtil.setLayoutMangerVertical(mRecyclerviewMw, this);
        mRecyclerviewMw.setAdapter(mAdapterEdt);
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD, tags = {@Tag("FLOW")})
    public void getFlowEdt(String edtMes) {
        LogUtil.util(TAG, "获取edt显示点击数据" + edtMes);
        Toast.makeText(getApplicationContext(), "获取edt显示点击数据" + edtMes, Toast.LENGTH_SHORT).show();
        mMarketSearchEdt.setText(edtMes);
    }

    @Override
    public void initListener() {
        super.initListener();
        if (mAdapterEdt != null)
            mAdapterEdt.setOnItemClickListener(this);
        if (mAdapter != null)
            mAdapter.setOnItemChildClickListener(this);
        RxTextView.textChanges(this.mMarketSearchEdt)//监听textview变化必须在ui线程
                .debounce(500, TimeUnit.MILLISECONDS)//每500毫秒请求一次
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Predicate<CharSequence>() {
                    @Override
                    public boolean test(CharSequence charSequence) throws Exception {
                        String s = charSequence.toString().trim();
                        boolean b = s.length() > 0;
                        changeData(s);
                        mRecyclerviewMm.setVisibility(b ? View.GONE : View.VISIBLE);
                        mRecyclerviewMw.setVisibility(b ? View.VISIBLE : View.GONE);
                        mSearchEdtClose.setVisibility(b ? View.VISIBLE : View.GONE);
                        return b;
                    }
                })
                //.subscribeOn(Schedulers.io())
                .flatMap(new Function<CharSequence, ObservableSource<ArrayList<String>>>() {
                    @Override
                    public ObservableSource<ArrayList<String>> apply(CharSequence charSequence) throws Exception {
                        //通过网络请求得到数据并发送  假数据  但是使用fltmap会每次都返回数据
                        mListKey = new ArrayList<>();
                        mListKey.add("长");
                        mListKey.add("段");
                        //如果使用rx+retrofit 直接返回
                        LogUtil.util(TAG, "返回数据是:" + mListKey.toString());
                        return Observable.just(mListKey);
                    }
                })
                /**
                 * 一定记得更新ui是observeOn 不是subscribeOn
                 * “subscribeOn()”这个方法是设定Observable所在线程
                 */
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ArrayList<String>>() {
                    @Override
                    public void accept(final ArrayList<String> strings) throws Exception {
                        mAdapter.setNewData(mList);
                        mAdapter.notifyDataSetChanged();

                        mAdapterEdt.setNewData(strings);
                        mAdapterEdt.notifyDataSetChanged();

                        TmtUtils.midToast(MarketSearchActivity.this, "搜索成功!" + strings.toString());
                    }
                });
    }

    private void changeData(String s) {
        if (!TextUtils.isEmpty(s)) {
            int size = mListFlow.size();
            if (size == 0)
                mListFlow.add(s);
            else {
                if (mListFlow.contains(s))
                    mListFlow.remove(s);
                else if (mListFlow.size() >= 10)
                    mListFlow.remove(mListFlow.size() - 1);

                mListFlow.add(0, s);
            }
        }
        mList.remove(0);
        mList.add(0, new MainItem(Constants.search_flow, mListFlow));
    }

    @OnClick({R.id.market_search_cancel, R.id.search_edt_close})
    public void OnClik(View v) {
        switch (v.getId()) {
            case R.id.market_search_cancel:
                finish();
                break;
            case R.id.search_edt_close:
                mMarketSearchEdt.setText("");
                break;

            default:
                break;
        }

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        mListFlow.clear();
        mList.remove(0);
        mList.add(0, new MainItem(Constants.search_flow, mListFlow));
        mAdapter.setNewData(mList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putString("Title",mListKey.get(position));
       showActivity (MarketSearchActivity.this, ExchangeActivity.class,bundle);
    }
}
